<template>
  <div class="member-management">
    <ReCommonTable
      ref="tableRef"
      title="会员管理"
      :loading="loading"
      :data="tableData"
      :columns="columns"
      :search-fields="searchFields"
      :pagination="pagination"
      @search="handleSearch"
      @refresh="handleRefresh"
      @size-change="handleSizeChange"
      @current-change="handleCurrentPageChange"
      @selection-change="handleSelectionChange"
    >
      <!-- 添加按钮 -->
      <template #toolbar-add>
        <el-button
          type="primary"
          size="small"
          :icon="CirclePlus"
          @click="handleAdd"
          >添加管理员
        </el-button>
      </template>
      <template #astatus="{ row }">
        <el-switch
          v-model="row.a_status"
          active-value="1"
          inactive-value="-1"
          inline-prompt
          active-text="有效"
          inactive-text="无效"
          size="small"
          :loading="row._switchLoading"
          @click="handleSwitchChange(row)"
        />
      </template>
      <!-- 操作列 -->
      <template #action="{ row }">
        <el-button size="small" @click="handleView(row)"> 查看</el-button>
        <el-button size="small" @click="handleEdit(row)"> 编辑</el-button>
        <el-button
          size="small"
          type="danger"
          @click="handleChangePassword(row)"
        >
          修改密码
        </el-button>
      </template>
    </ReCommonTable>

    <!--详情弹窗 -->
    <el-dialog
      v-model="detailVisible"
      title="管理员详情"
      width="600px"
      :close-on-click-modal="false"
    >
      <div v-if="currentAdmin" class="member-detail">
        <el-descriptions :column="1" border>
          <el-descriptions-item label="账号">
            {{ currentAdmin.a_uname }}
          </el-descriptions-item>
          <el-descriptions-item label="姓名">
            {{ currentAdmin.a_name || "未填写" }}
          </el-descriptions-item>
          <el-descriptions-item label="手机号">
            {{ currentAdmin.a_mobile }}
          </el-descriptions-item>
          <el-descriptions-item label="状态">
            {{ currentAdmin.status }}
          </el-descriptions-item>
        </el-descriptions>
      </div>

      <template #footer>
        <el-button @click="detailVisible = false">关闭</el-button>
      </template>
    </el-dialog>

    <!-- 管理员编辑弹窗 -->
    <el-dialog
      v-model="editVisible"
      title="编辑管理员"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="editFormRef"
        :model="editForm"
        :rules="editRules"
        label-width="80px"
      >
        <el-form-item v-if="isAdding" label="账号" prop="uname">
          <el-input v-model="editForm.uname" placeholder="请输入账号" />
        </el-form-item>
        <el-form-item v-if="isAdding" label="密码" prop="pwd">
          <el-input v-model="editForm.pwd" placeholder="请输入密码" />
        </el-form-item>
        <el-form-item label="姓名" prop="name">
          <el-input v-model="editForm.name" placeholder="请输入姓名" />
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="editForm.mobile" placeholder="请输入手机号" />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="editVisible = false">取消</el-button>
        <el-button
          v-if="isAdding === false"
          type="primary"
          :loading="editLoading"
          @click="handleSaveEdit"
        >
          保存
        </el-button>
        <el-button
          v-if="isAdding === true"
          type="primary"
          :loading="editLoading"
          @click="handleSaveAdd"
        >
          添加
        </el-button>
      </template>
    </el-dialog>

    <!-- 修改密码弹窗 -->
    <el-dialog
      v-model="passwordVisible"
      title="修改密码"
      width="500px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="passwordFormRef"
        :model="{ ...passwordForm, confirm_pwd: confirmPassword }"
        :rules="passwordRules"
        label-width="80px"
      >
        <el-form-item label="原密码" prop="pwd">
          <el-input
            v-model="passwordForm.pwd"
            type="password"
            placeholder="请输入原密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="新密码" prop="new_pwd">
          <el-input
            v-model="passwordForm.new_pwd"
            type="password"
            placeholder="请输入新密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirm_pwd">
          <el-input
            v-model="confirmPassword"
            type="password"
            placeholder="请再次输入新密码"
            show-password
          />
        </el-form-item>
      </el-form>

      <template #footer>
        <el-button @click="passwordVisible = false">取消</el-button>
        <el-button
          type="primary"
          :loading="passwordLoading"
          @click="handleSavePassword"
        >
          确认修改
        </el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from "vue";
import { ElMessageBox, ElMessage } from "element-plus";
import { CirclePlus } from "@element-plus/icons-vue";
import { ReCommonTable } from "@/components/ReCommonTable";
import type {
  SearchField,
  TableColumn
} from "@/components/ReCommonTable/src/index.vue";
import {
  getAdminList,
  editAdmin,
  delAdmin,
  addAdmin,
  editAdminPwd,
  type AddAdminParams,
  type EditAdminParams,
  type EditPwdParams,
  type Admin,
  type AdminListParams
} from "@/api/admin";

defineOptions({
  name: "AdminList"
});

// 响应式数据
const loading = ref(false);
const detailVisible = ref(false);
const editVisible = ref(false);
const editLoading = ref(false);
const tableRef = ref();
const editFormRef = ref();
const selectedRows = ref([]);
const currentAdmin = ref<Admin | null>(null);

// 修改密码弹窗相关
const passwordVisible = ref(false);
const passwordLoading = ref(false);
const passwordFormRef = ref();
const currentAdminId = ref("");

// 搜索表单
const searchForm = ref<AdminListParams>({});

// 表格数据
const tableData = ref([]);

// 分页配置
const pagination = reactive({
  current: 1,
  size: 10,
  total: 0,
  pageSizes: [10, 20, 50, 100],
  layout: "total, sizes, prev, pager, next, jumper",
  background: true,
  disabled: false,
  paginationSize: "default"
});

// 搜索字段配置（根据API文档）
const searchFields: SearchField[] = [
  {
    prop: "keys",
    label: "关键字",
    type: "input",
    placeholder: "请输入账号、手机号或手机号后4位"
  }
];

// 表格列配置（根据API文档字段）
const columns: TableColumn[] = [
  {
    prop: "a_id",
    label: "id"
  },
  {
    prop: "a_uname",
    label: "账号",
    showOverflowTooltip: true
  },
  {
    prop: "a_name",
    label: "姓名",
    width: 140
  },
  {
    prop: "a_mobile",
    label: "手机号"
  },
  {
    prop: "a_status",
    label: "状态",
    slot: "astatus"
  },
  {
    label: "操作",
    fixed: "right",
    slot: "action"
  }
];

// 格式化时间戳
const formatTimestamp = (timestamp: string) => {
  if (!timestamp || timestamp === "0") return "";
  const date = new Date(parseInt(timestamp) * 1000);
  return date.toLocaleString("zh-CN", {
    year: "numeric",
    month: "2-digit",
    day: "2-digit",
    hour: "2-digit",
    minute: "2-digit",
    second: "2-digit"
  });
};

// 事件处理
const handleSearch = (searchParams: any) => {
  console.log("搜索参数:", searchParams);
  searchForm.value = searchParams;
  pagination.current = 1;
  loadData();
};

const handleRefresh = () => {
  loadData();
};

const handleSizeChange = (size: number) => {
  pagination.size = size;
  pagination.current = 1;
  loadData();
};

const handleCurrentPageChange = (current: number) => {
  pagination.current = current;
  loadData();
};

const handleSelectionChange = (selection: any[]) => {
  selectedRows.value = selection;
};

const handleView = (row: any) => {
  currentAdmin.value = row;
  detailVisible.value = true;
};
// 加载数据
const loadData = async () => {
  loading.value = true;

  try {
    const params: AdminListParams = {
      num: pagination.size.toString(),
      page: pagination.current.toString(),
      ...searchForm.value
    };

    // 尝试调用API
    try {
      const response = await getAdminList(params);

      if (response.code === 1) {
        tableData.value = response.data.list;
        pagination.total = response.data.list.length; // 假设API返回的总页数
        //pagination.total = response.data.pages * pagination.size;
        return;
      } else {
        ElMessage.error(response.msg || "数据加载失败");
      }
    } catch (apiError) {
      console.error("API调用错误:", apiError);
      ElMessage.error("数据加载失败，请稍后重试");
    }
  } catch (error) {
    console.error("数据加载错误:", error);
    ElMessage.error("数据加载失败");
  } finally {
    loading.value = false;
  }
};

const isAdding = ref(false);
// 编辑表单
const editForm = ref<EditAdminParams>({
  id: "",
  uname: "",
  pwd: "",
  name: "",
  mobile: ""
});

// 编辑表单验证规则
const editRules = {
  uname: [
    { required: true, message: "请输入账号", trigger: "blur" },
    { min: 1, max: 20, message: "账号长度在3到20个字符之间", trigger: "blur" }
  ],
  pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在6到20个字符之间", trigger: "blur" }
  ],
  name: [{ required: true, message: "请输入姓名", trigger: "blur" }],
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    { pattern: /^1[3-9]\d{9}$/, message: "请输入正确的手机号", trigger: "blur" }
  ]
};

// 修改密码表单
const passwordForm = ref<EditPwdParams>({
  id: "",
  pwd: "",
  new_pwd: ""
});

// 确认密码字段（用于表单验证）
const confirmPassword = ref("");

// 修改密码表单验证规则
const passwordRules = {
  pwd: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  new_pwd: [
    { required: true, message: "请输入新密码", trigger: "blur" },
    { min: 6, max: 20, message: "密码长度在 6 到 20 个字符", trigger: "blur" }
  ],
  confirm_pwd: [
    { required: true, message: "请再次输入新密码", trigger: "blur" },
    {
      validator: (rule: any, value: string, callback: any) => {
        if (value !== passwordForm.value.new_pwd) {
          callback(new Error("两次输入的密码不一致"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

const handleEdit = (row: any) => {
  editForm.value = {
    id: row.a_id,
    name: row.a_name || "",
    mobile: row.a_mobile || ""
  };
  isAdding.value = false; // 标记为编辑操作
  editFormRef.value?.resetFields(); // 重置表单验证状态
  // 如果是编辑操作，uname和pwd不需要显示
  editVisible.value = true;
};

const handleSaveEdit = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const response = await editAdmin(editForm.value);

    if (response.code === 1) {
      ElMessage.success(response.msg || "编辑成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "编辑失败");
    }
  } catch (error) {
    console.error("编辑会员失败:", error);
    ElMessage.error("编辑失败");
  } finally {
    editLoading.value = false;
  }
};
const handleAdd = () => {
  // 初始化表单数据
  editForm.value = {
    id: "",
    uname: "",
    pwd: "",
    name: "",
    mobile: ""
  };
  isAdding.value = true; // 标记为添加操作
  editFormRef.value?.resetFields(); // 重置表单验证状态
  editVisible.value = true; // 显示编辑弹窗（复用编辑弹窗）
};
const handleSaveAdd = async () => {
  if (!editFormRef.value) return;

  try {
    await editFormRef.value.validate();
    editLoading.value = true;

    const params: AddAdminParams = {
      uname: editForm.value.uname,
      pwd: editForm.value.pwd,
      name: editForm.value.name,
      mobile: editForm.value.mobile
    };

    const response = await addAdmin(params);

    if (response.code === 1) {
      ElMessage.success(response.msg || "添加成功");
      editVisible.value = false;
      loadData(); // 重新加载数据
    } else {
      ElMessage.error(response.msg || "添加失败");
    }
  } catch (error) {
    console.error("添加管理员失败:", error);
    ElMessage.error("添加失败");
  } finally {
    editLoading.value = false;
  }
};
// 删除操作
const handleSwitchChange = async (row: any) => {
  try {
    // 设置 loading 状态
    row._switchLoading = true;
    // 调用更新状态的 API，比如 delAdmin
    const response = await delAdmin(row.a_id);
    if (response.code == 1) {
      ElMessage.success("状态更新成功");
    } else {
      ElMessage.error("状态更新失败");
      row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
    }
  } catch (error) {
    console.error("状态更新出错:", error);
    ElMessage.error("状态更新失败");
    row.t_status = row.t_status === 1 ? -1 : 1; // 回滚状态
  } finally {
    // 清除 loading
    row._switchLoading = false;
  }
  await loadData();
};

// 修改密码相关方法
const handleChangePassword = (row: any) => {
  currentAdminId.value = row.a_id;
  passwordForm.value = {
    id: row.a_id,
    pwd: "",
    new_pwd: ""
  };
  confirmPassword.value = "";
  passwordFormRef.value?.resetFields();
  passwordVisible.value = true;
};

const handleSavePassword = async () => {
  if (!passwordFormRef.value) return;

  try {
    await passwordFormRef.value.validate();
    passwordLoading.value = true;

    const response = await editAdminPwd(passwordForm.value);

    if (response.code === 1) {
      ElMessage.success(response.msg || "密码修改成功");
      passwordVisible.value = false;
    } else {
      ElMessage.error(response.msg || "密码修改失败");
    }
  } catch (error) {
    console.error("修改密码失败:", error);
    ElMessage.error("修改密码失败");
  } finally {
    passwordLoading.value = false;
  }
};

// 生命周期
onMounted(() => {
  loadData();
});
</script>

<style scoped>
.member-management {
  height: 100%;
  background: #f5f7fa;
}

.member-detail {
  max-height: 500px;
  overflow-y: auto;
}

:deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #fafafa;
}

.dark :deep(.el-descriptions) {
  --el-descriptions-item-bordered-label-background: #262727;
}
</style>
